package almacen;

import resources.local_connection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Homeroe
 */
public class agregarCategorias extends javax.swing.JFrame {
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    int idSelected = -1;
    DefaultListModel model1 = new DefaultListModel();
    /**
     * Creates new form agregarCategorias
     */
    public agregarCategorias() {
        initComponents();
            try {
            cn = local_connection.getconnect();
            ps = (PreparedStatement) cn.prepareStatement("SELECT nombre FROM categorias");
            rs = ps.executeQuery();
            while (rs.next()) {
                model1.addElement(rs.getString(1));
            }
            listCategorias.setModel(model1);
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listCategorias = new javax.swing.JList();
        buttonOk = new javax.swing.JButton();
        buttonCancelar = new javax.swing.JButton();
        labelId = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textDescripcion = new javax.swing.JTextArea();
        buttonNew = new javax.swing.JButton();
        buttonBorrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Categorias");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());

        listCategorias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listCategoriasMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listCategorias);

        buttonOk.setText("Guardar");
        buttonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOkActionPerformed(evt);
            }
        });

        buttonCancelar.setText("Salir");
        buttonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelarActionPerformed(evt);
            }
        });

        labelId.setText("ID: ");

        jLabel2.setText("Nombre");

        jLabel3.setText("Descripcion");

        textDescripcion.setColumns(20);
        textDescripcion.setLineWrap(true);
        textDescripcion.setRows(5);
        textDescripcion.setWrapStyleWord(true);
        jScrollPane2.setViewportView(textDescripcion);

        buttonNew.setText("Nuevo...");
        buttonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNewActionPerformed(evt);
            }
        });

        buttonBorrar.setText("Borrar");
        buttonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBorrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonNew, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(buttonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textNombre)
                            .addComponent(jScrollPane2)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelId)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 102, Short.MAX_VALUE)
                                .addComponent(buttonOk)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonBorrar)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelId)
                            .addComponent(buttonBorrar)
                            .addComponent(buttonOk))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancelar)
                    .addComponent(buttonNew))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed
        if (idSelected != -1){
            try {
                ps = (PreparedStatement) cn.prepareStatement("UPDATE categorias SET nombre='"+textNombre.getText()+"', descripcion='"+textDescripcion.getText()+"' WHERE id_categoria = "+idSelected);
                ps.execute();
                model1.setElementAt(textNombre.getText(), listCategorias.getSelectedIndex());
            } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }
    }//GEN-LAST:event_buttonOkActionPerformed

    private void loadDatos(){
        try {
            ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM categorias WHERE nombre = '"+model1.getElementAt(listCategorias.getSelectedIndex())+"' LIMIT 1");            
            rs = ps.executeQuery();
            while(rs.next()){
                idSelected = rs.getInt("id_categoria");
                labelId.setText("ID: "+idSelected);
                textNombre.setText(rs.getString("nombre"));
                textDescripcion.setText(rs.getString("descripcion"));
            }
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }
    
    private void buttonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCancelarActionPerformed

    private void listCategoriasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listCategoriasMouseClicked
        if (listCategorias.getSelectedIndex() != -1) {
           loadDatos();
        }
    }//GEN-LAST:event_listCategoriasMouseClicked

    private void buttonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNewActionPerformed
        try {
            ps = (PreparedStatement) cn.prepareStatement("INSERT INTO categorias(nombre,descripcion) VALUES('- - -','')");
            ps.execute();
            model1.addElement("- - -");
            listCategorias.setSelectedIndex(model1.lastIndexOf(model1.lastElement()));
            loadDatos();
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_buttonNewActionPerformed

    private void buttonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBorrarActionPerformed
        try {
            Object[] options = {"Si","No"};
            int n = JOptionPane.showOptionDialog(null,"¿Realmente quieres borrar la categoria: "+textNombre.getText()+"?",
            "Borrar categoria",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE,
            null,
            options,
            options[1]);
            switch(n){
                case(0): 
                    ps = (PreparedStatement) cn.prepareStatement("DELETE FROM categorias WHERE id_categoria="+idSelected);
                    ps.execute();
                    model1.removeElementAt(listCategorias.getSelectedIndex());
                    listCategorias.setSelectedIndex(model1.lastIndexOf(model1.lastElement()));
                    loadDatos();
                    break;
                case(1): break;
                default: break;
            }
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_buttonBorrarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBorrar;
    private javax.swing.JButton buttonCancelar;
    private javax.swing.JButton buttonNew;
    private javax.swing.JButton buttonOk;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelId;
    private javax.swing.JList listCategorias;
    private javax.swing.JTextArea textDescripcion;
    private javax.swing.JTextField textNombre;
    // End of variables declaration//GEN-END:variables
}
